package com.dianrui.agent.activity;


import android.graphics.Color;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;


import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.dianrui.agent.R;
import com.dianrui.agent.bean.BikePointModel;

import com.dianrui.agent.okhttp.OkHttpRequest;
import com.dianrui.agent.util.SharedUtil;
import com.dianrui.agent.util.StringUtils;
import com.dianrui.agent.util.ToastUtil;
import com.dianrui.agent.util.Url;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 显示位置
 *
 * @author Administrator
 */
public class ShowNetworkMapActivity extends BaseActivity {
    private AMap aMap;
    private Marker clickMaker;
    private List<BikePointModel> carPointList = new ArrayList<>();
    private List<LatLng> points = new ArrayList<>();
    private List<LatLng> mAreaPoints = new ArrayList<>();


    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.mapviews)
    MapView mapviews;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapviews.onCreate(savedInstanceState);

    }

    @Override
    public int getContentViewId() {
        return R.layout.show_location;
    }

    @Override
    public void initView() {
        title.setText(getString(R.string.return_point));
        if (aMap == null) {
            aMap = mapviews.getMap();
        }
        UiSettings mUiSettings = aMap.getUiSettings();
        mUiSettings.setTiltGesturesEnabled(false);
        mUiSettings.setRotateGesturesEnabled(false);
        mUiSettings.setZoomControlsEnabled(false);
        network();
        aMap.setOnMarkerClickListener(markerClickListener);
        aMap.setInfoWindowAdapter(infoWindowAdapter);
        aMap.setOnInfoWindowClickListener(listener);
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if (clickMaker != null && clickMaker.isInfoWindowShown()) {
                    clickMaker.hideInfoWindow();
                }
            }
        });
        getArea();
    }

    //获取还车点
    private void network() {
        OkHttpRequest.getInstance().postTokenRequests(SharedUtil.getUrl() + Url.NETWORK, "", new OkHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject != null && !isFinishing()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                if (carPointList != null) {
                                    carPointList.clear();
                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        BikePointModel bike = new BikePointModel();
                                        bike.name = jsonArray.optJSONObject(i).optString("name");
                                        bike.city_path = jsonArray.optJSONObject(i).optString("city_path");
                                        bike.lat = jsonArray.optJSONObject(i).optDouble("glat");
                                        bike.lng = jsonArray.optJSONObject(i).optDouble("glng");
                                        carPointList.add(bike);
                                        if ("1".equals(jsonArray.optJSONObject(i).optString("fixed_type"))) {
                                            List<LatLng> points = new ArrayList<>();
                                            View view = View.inflate(ShowNetworkMapActivity.this, R.layout.over_park_area, null);
                                            Marker marker = aMap.addMarker(new MarkerOptions().position(new LatLng(carPointList.get(i).lat, carPointList.get(i).lng)).icon(BitmapDescriptorFactory.fromView(view)));
                                            marker.setObject(carPointList.get(i));

                                            if (points != null) {
                                                points.clear();
                                            }
                                            JSONArray jsonArray3 = jsonArray.optJSONObject(i).optJSONArray("fixed_path");
                                            if (jsonArray3.length() > 0) {
                                                for (int j = 0; j <= jsonArray3.length(); j++) {
                                                    if (j == jsonArray3.length()) {
                                                        JSONObject jsonObject1 = jsonArray3.optJSONObject(0);
                                                        points.add(new LatLng(jsonObject1.optDouble("lat"), jsonObject1.optDouble("lng")));
                                                    } else {
                                                        JSONObject jsonObject1 = jsonArray3.optJSONObject(j);
                                                        points.add(new LatLng(jsonObject1.optDouble("lat"), jsonObject1.optDouble("lng")));
                                                    }
                                                }
                                                if (points.size() < 2) {
                                                    return;
                                                }
                                                if (points.size() > 0) {
                                                    List<BitmapDescriptor> textureList = new ArrayList<>();
                                                    textureList.add(BitmapDescriptorFactory.fromResource(R.mipmap.customer_img));

                                                    List<Integer> textureIndexs = new ArrayList<>();
                                                    textureIndexs.add(i);
                                                    aMap.addPolyline(new PolylineOptions().
                                                            addAll(points).width(4).setCustomTextureList(textureList).setCustomTextureIndex(textureIndexs).setDottedLine(true));
                                                }


                                            }
                                        }
                                    }

                                    if (carPointList.size() > 0) {
                                        title.setText(getString(R.string.return_point) + "(" + carPointList.size() + ")");
                                    } else {
                                        title.setText(getString(R.string.return_point));
                                    }

                                }
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void FailedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    private void getArea() {
        if (!StringUtils.isEmpty(spUtils.getString("area"))) {
            if (!StringUtils.isEmpty(spUtils.getString("area"))&&!isFinishing()) {
                try {
                    final JSONObject jsonObject = new JSONObject(spUtils.getString("area"));
                    if (jsonObject != null) {
                        if (mAreaPoints != null) {
                            mAreaPoints.clear();
                        }
                        JSONArray gfixed_path = jsonObject.optJSONObject("data").optJSONArray("fixed_path");
                        if (gfixed_path.length() > 0) {
                            for (int j = 0; j < gfixed_path.length(); j++) {
                                JSONObject jsonObject3 = gfixed_path.optJSONObject(j);
                                mAreaPoints.add(new LatLng(jsonObject3.optDouble("lat"), jsonObject3.optDouble("lng")));
                            }

                            if (mAreaPoints.size() > 0) {
                                PolygonOptions polygonOptions = new PolygonOptions();
                                polygonOptions.addAll(mAreaPoints);
                                polygonOptions.strokeWidth(4);
                                polygonOptions.strokeColor(Color.rgb(255, 0, 0));
                                polygonOptions.fillColor(Color.argb(0, 255, 0, 0));
                                aMap.addPolygon(polygonOptions);
                            }
                            LatLngBounds.Builder b = LatLngBounds.builder();
                            for (LatLng latLng : mAreaPoints) {
                                b.include(latLng);
                            }
                            LatLngBounds bounds = b.build();
                            aMap.moveCamera(CameraUpdateFactory.newLatLngBoundsRect(bounds, 80, 80, 230, 260));
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    // 定义 Marker 点击事件监听
    AMap.OnMarkerClickListener markerClickListener = new AMap.OnMarkerClickListener() {
        // marker 对象被点击时回调的接口
        // 返回 true 则表示接口已响应事件，否则返回false
        @Override
        public boolean onMarkerClick(final Marker marker) {
            clickMaker = marker;
            marker.showInfoWindow();
            return true;
        }
    };

    //显示infowindow
    AMap.InfoWindowAdapter infoWindowAdapter = new AMap.InfoWindowAdapter() {
        @Override
        public View getInfoWindow(Marker marker) {
            View view = LayoutInflater.from(ShowNetworkMapActivity.this).inflate(R.layout.show_network_bubble, null);
            TextView name = view.findViewById(R.id.name);
            TextView address = view.findViewById(R.id.address);
            BikePointModel bikePointModel = (BikePointModel) marker.getObject();
            name.setText(bikePointModel.name);
            address.setText(bikePointModel.city_path);
            return view;
        }

        @Override
        public View getInfoContents(Marker marker) {
            return null;
        }
    };

    //点击marker就消失
    AMap.OnInfoWindowClickListener listener = new AMap.OnInfoWindowClickListener() {

        @Override
        public void onInfoWindowClick(Marker marker) {
            marker.hideInfoWindow();
        }
    };

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapviews.onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapviews.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapviews.onPause();
    }

    @OnClick(R.id.back)
    public void onViewClicked() {
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapviews.onDestroy();
        if (mAreaPoints != null) {
            mAreaPoints.clear();
        }

    }
}
